package com.syqc.monitor.ui.carmonitor

import android.view.Gravity
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import autodispose2.autoDispose
import com.syqc.comlib.GuideControl.isShowLinePopup
import com.syqc.comlib.base.LazyFragment
import com.syqc.comlib.custom.timer.CustomDatePicker
import com.syqc.comlib.custom.timer.DateFormatUtils
import com.syqc.comlib.utils.CalendarUtil
import com.syqc.comlib.utils.startActivityTo
import com.syqc.comlib.utils.toast
import com.syqc.monitor.ParamsUtil
import com.syqc.monitor.R
import com.syqc.monitor.databinding.FragmentCarLineBinding
import com.syqc.monitor.databinding.IncludeChooseTimeBinding
import com.syqc.monitor.databinding.IncludeSelectSureBinding
import com.syqc.monitor.ui.historyline.HistoryLineInfoActivity
import com.syqc.monitor.ui.historyline.HistoryLinePopup
import com.syqc.monitor.ui.historyline.HistoryMilePopup
import com.syqc.adapter.ChooseTimeAdapter
import com.syqc.utils.Keys
import com.syqc.utils.TimeUtil
import com.syqc.utils.ToolsUtil
import com.syqc.videos.CarMonitorViewModel

/**
 *@Author Jasper
 *@Time   2020/7/22
 *@Desc   车辆 历史轨迹
 */
class CarHistoryLineFragment :
    LazyFragment<FragmentCarLineBinding>(FragmentCarLineBinding::inflate) {
    private lateinit var mChooseTimeVB: IncludeChooseTimeBinding
    private lateinit var mTureVB: IncludeSelectSureBinding

    //是否首次进入
    private var isFirst = true

    private val mViewModel: HistoryLineViewModel by viewModels()
    private val mActivityVM by activityViewModels<CarMonitorViewModel>()

    private val mAdapter: ChooseTimeAdapter by lazy { ChooseTimeAdapter() }

    private val mMilePopup by lazy { HistoryMilePopup(requireContext()) }

    private val mDatePicker: CustomDatePicker by lazy {
        CustomDatePicker(
            requireContext(),
            callback,
            TimeUtil.normalDate,
            mViewModel.nowTimeFormat(),
            true
        ).apply {
            setCanShowPreciseTime(true)
        }
    }

    private val mPopup by lazy {
        HistoryLinePopup(requireContext(), { time ->
            mAdapter.index = -1
            mAdapter.notifyDataSetChanged()
            mChooseTimeVB.lrvStartTime.setRightText("$time 00:00")
            mChooseTimeVB.lrvEndTime.setRightText("$time 23:59")
        }, { sTime, eTime ->
            mViewModel.getDayMile(sTime, eTime)
        })
    }

    override fun initData() {
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)

        binding.recyclerTime.layoutManager = GridLayoutManager(context, 4)
        binding.recyclerTime.adapter = mAdapter.apply {
            setNewInstance(mViewModel.timeList)
            setOnItemClickListener { _, _, position ->
                index = position
                notifyDataSetChanged()
                mViewModel.chooseTime(position)
            }
        }

        mViewModel.startObserve().autoDispose(scopeProvider).subscribe {
            mChooseTimeVB.lrvStartTime.setRightText(it)
        }

        mViewModel.endObserve().autoDispose(scopeProvider).subscribe {
            mChooseTimeVB.lrvEndTime.setRightText(it)
        }

        mViewModel.historyLineObserver().autoDispose(scopeProvider).subscribe {
            var speed = binding.editThresholdSpeed.text.toString()
            if (speed.isEmpty()) speed = "0"

               startActivityTo<HistoryLineInfoActivity>(requireContext()) {
                    putExtra(Keys.INTENT_TITLE, mViewModel.carName)
                    putExtra(Keys.INTENT_OTHER, speed)
                    putExtra(Keys.INTENT_DATA, mViewModel.params)
                    putExtra(Keys.INTENT_CAR_ID, mViewModel.carId)
                    putExtra(Keys.VIDEO, mViewModel.videos)
                }
        }
    }


    override fun initView(view: View) {
        mChooseTimeVB = IncludeChooseTimeBinding.bind(binding.root)
        mTureVB = IncludeSelectSureBinding.bind(binding.root)
        setParams()
        mActivityVM.carId.observe(this) {
            mViewModel.carId = it
            isFirst = true
        }
        mActivityVM.carName.observe(this) {
            mViewModel.carName = it
        }
        mActivityVM.videos.observe(this) {
            mViewModel.videos = it
        }
        mTureVB.tvSure.postDelayed({
            if (mViewModel.carId.isEmpty()) {
                R.string.hint_toast_choose_car.toast(requireContext())
            }
        }, 100)

        mViewModel.mileLive.observe(this) {
            mPopup.setData(it)
            if (isFirst) {
                isFirst = false
                mPopup.showAtLocation(binding.root, Gravity.NO_GRAVITY, 0, 0)
            }
        }

    }

    private fun setParams() {
        val lineParams = ParamsUtil.getLineParams()
        binding.editThresholdSpeed.setText(lineParams?.get(0) ?: "100")
        binding.editThresholdStop.setText(lineParams?.get(1) ?: "5")
    }

    override fun initEvent() {
        if (isShowLinePopup) {
            mMilePopup.showAtLocation(binding.root, Gravity.NO_GRAVITY, 0, 0)
            isShowLinePopup = false
        }
        mChooseTimeVB.lrvStartTime.rightClick {
            mViewModel.isStart = true
            mDatePicker.show(mChooseTimeVB.lrvStartTime.getRightText())
        }

        mChooseTimeVB.lrvEndTime.rightClick {
            mViewModel.isStart = false
            mDatePicker.show(mChooseTimeVB.lrvEndTime.getRightText())
        }

        mTureVB.tvSure.setOnClickListener {
            if (ToolsUtil.isFastClick()) return@setOnClickListener
            mViewModel.getHistory(
                mChooseTimeVB.lrvStartTime.getRightText(),
                mChooseTimeVB.lrvEndTime.getRightText(),
                binding.cbFilterStop.isChecked,
                binding.editThresholdSpeed.text.toString(),
                binding.editThresholdStop.text.toString(),
                binding.cbFilterInvalid.isChecked,
                binding.cbFilterAppend.isChecked
            )
            ParamsUtil.saveLineParams(
                binding.editThresholdSpeed.text.toString(),
                binding.editThresholdStop.text.toString()
            )
        }

        binding.ivCalendar.setOnClickListener {
            if (mViewModel.carId.isEmpty()) {
                showToast(R.string.hint_toast_choose_car)
                return@setOnClickListener
            }
            if (isFirst) {
                val curYear = CalendarUtil.getCurYear()
                val curMonth = CalendarUtil.getCurMonth()
                val curDay = CalendarUtil.getCurDay()
                val lastDay = CalendarUtil.getYMStartDay(curYear, curMonth)
                val sTime = getYMDStr(curYear, curMonth, lastDay)
                val eTime = getYMDStr(curYear, curMonth, curDay)
                mViewModel.getDayMile(sTime, eTime)
                mPopup.setCurCalender(curYear, curMonth, curDay)
            } else {
                mPopup.showAtLocation(binding.root, Gravity.NO_GRAVITY, 0, 0)
            }
        }
    }

    private val callback: CustomDatePicker.Callback = object : CustomDatePicker.Callback {
        override fun onTimeSelected(timestamp: Long) {
            mAdapter.index = -1
            mAdapter.notifyDataSetChanged()
            val time: String = DateFormatUtils.long2Str(timestamp, true)

            if (mViewModel.isStart) {
                mChooseTimeVB.lrvStartTime.setRightText(time)
            } else {
                mChooseTimeVB.lrvEndTime.setRightText(time)
            }
            mDatePicker.dismiss()
        }
    }

    private fun getYMDStr(year: Int, month: Int, day: Int): String {
        val nMonth = if (month < 10) "0$month" else "$month"
        val nDay = if (day < 10) "0$day" else "$day"
        return "$year$nMonth$nDay"
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (mPopup.isShowing) mPopup.dismiss()
        if (mMilePopup.isShowing) mMilePopup.dismiss()
    }
}